package com.android.xk.mask.client

import com.android.xk.mask.model.DataPost
import com.android.xk.mask.model.Message
import com.android.xk.mask.model.MessageResult
import com.android.xk.mask.model.SystemMonitor
import com.android.xk.mask.writeString
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder
import java.nio.charset.Charset

class MessageEncoder : MessageToByteEncoder<Message>()
{
    override fun encode(ctx: ChannelHandlerContext, msg: Message, out: ByteBuf)
    {
        out.writeInt(msg.msgLen)
        out.writeInt(msg.msgId)
        out.writeInt(msg.sequence)
        out.writeString(msg.version, 16)
        out.writeCharSequence(msg.deviceId, Charset.defaultCharset())
//        val v = msg.version.toByteArray()
//        out.writeBytes(v)
//        val s = ByteArray(16 - v.size)
//        for (i in s.indices)
//        {
//            s[i] = 0
//        }
//        out.writeBytes(s)
        when (msg.msgId)
        {
            0x0F000002, 0x0F000008, 0x0F000010,0x0F000012 ->
            {
                val messageResult = msg.userData as MessageResult
                out.writeByte(messageResult.result)
                out.writeByte(messageResult.errorCode)
            }
            0x0F000003                         ->
            {
                val systemMonitor = msg.userData as SystemMonitor
                out.writeByte(systemMonitor.rssi)
                out.writeByte(systemMonitor.cpuRate)
                out.writeByte(systemMonitor.memRate)
                out.writeByte(systemMonitor.hddRate)
                out.writeInt(systemMonitor.upRate)
                out.writeInt(systemMonitor.downRate)
                out.writeString(systemMonitor.longitude, 16)
                out.writeString(systemMonitor.latitude, 16)
            }
            0x0F000005                         ->
            {
                val dataPost = msg.userData as DataPost
                out.writeByte(dataPost.displayArea)
                out.writeInt(dataPost.resoureId)
                out.writeByte(dataPost.timeType)
                out.writeString(dataPost.time, 16)
            }
        }
    }
}